const R = require('ramda')
const { MenuNotFoundError } = require('../../domain/menu/error')

const Usecase = require('../../shared/usecase/Usecase')

class UpdateMenu extends Usecase {
  constructor({ database, menuRepo, currentUser }) {
    super()
    this.menuRepo = menuRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }

  async checkIdAndGet(id) {
    const menu = await this.menuRepo.findById(id)
    if (!menu) throw new MenuNotFoundError(id)
    return menu
  }

  async execute(data) {
    const menu = await this.checkIdAndGet(data.id)
    Object.assign(menu, R.omit(['code'], data))
    const transaction = await this.sequelize.transaction()
    try {
      await this.menuRepo.update(menu, {
        transaction,
      })
      await transaction.commit()
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = UpdateMenu
